# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: JHC000abc@gmail.com
@file: script_3.py
@time: 2024/10/30 19:50 
@desc: 

"""
from sdk.temp.temp_supports import IsSolution
from sdk.utils.util_class import PathParser
from sdk.utils.util_times import TimeProcess
from sdk.utils.util_compress import ZipProcess


class Solution(IsSolution):
    """

    """

    def __init__(self):
        super(Solution, self).__init__()
        self.desc = f"script3_1556_判卷"
        print(self.desc)
        self.time = TimeProcess()
        self.zip = ZipProcess()
        self.q_map = {
            "1": "视频无问题",
            "2": "1.字幕影响主画面（仅横屏）",
            "3": "2.字幕前后不在一个水平线",
            "4": "3.字幕遮挡不完全",
            "5": "4.字幕擦除不干净",
            "6": "5.字幕重复/重叠/串行",
            "7": "6.无关/生硬拼接",
            "8": "7.音、视频有硬伤",
            "9": "8.音、视频表述不完整/被截断",
            "10": "9.内容画面杂乱",
            "11": "10.低俗色情",
            "12": "11.音画不一致",
            "13": "12.内容引起不适",
            "14": "13.内容中有站外联系方式",
            "15": "14.视频画幅不和谐",
            "16": "15.背景音乐紧张",
            "17": "16.文品一致性",
            "18": "17.通顺度",
            "19": "18.出现利益点、价格信息",
            "20": "19.出现时效信息",
            "21": "20.生成其他文案",
            "22": "无",
        }

    def get_stand_map(self, file, sheet):
        """

        :param file:
        :return:
        """
        map = {}
        for args in self.excel.read_yield_by_pandas(file, sheets=[sheet]):
            if sheet in ("练习2更新答案", "练习3_20", "脚本考试"):
                map[args["num"]] = sorted([i for i in args["line"][-2:] if str(i) not in ("nan", "无")])
            else:
                map[args["num"]] = sorted([i for i in args["line"][-3:] if str(i) not in ("nan", "无")])
        return map

    def get_out_headers(self, stand_map):
        """

        :param stand_map:
        :return:
        """
        _out_headers = []
        for i in range(len(stand_map)):
            _out_headers.extend([f"用户答案{i + 1}", f"标准答案{i + 1}", f"题目{i + 1}标签正确率"])
        return _out_headers

    def dp(self, input_file, stand_file, sheet, filename):
        stand_map = self.get_stand_map(stand_file, sheet)
        map_qid = {}
        map_error_q_id = {}
        _out_headers = self.get_out_headers(stand_map)

        answer_times = 0
        for args in self.csv.read_yield_csv(input_file):
            # print(args)
            answer_times += 1
            right_num = 0
            tag_right_num = 0
            tag_right_num_all = 0
            answer = self.json.loads(self.get_one_from_yield_args(args, "answer"))
            # print("answer",answer)
            base = ""
            name = ""
            phone = ""
            alliance = ""
            answer_args = answer["questions"][0]["answer"]
            for key, value in answer_args.items():
                if key == "base":
                    base = value
                elif key == "phone":
                    phone = value
                elif key == "alliance":
                    alliance = value
                elif key == "name":
                    name = value

            answer_lists = []

            out_lis = args["line"][:2] + [args["line"][3]] + [name, phone, base, alliance]
            # print(len(out_lis))
            error_recode = []
            user_all = 0
            stand_all = 0
            rec_num1 = 0
            rec_num2 = 0
            for index in range(len(stand_map)):
                user_answer = sorted(
                    [self.q_map.get(i.get("value")) for i in answer_args.get(f"label_1_0_{index}", []) if
                     i.get("value") != "22"])

                stand_answer = stand_map.get(index + 1)
                stand_all += len(stand_answer)

                answer_lists.append("\n".join(user_answer))
                answer_lists.append("\n".join(stand_answer))
                sig_ubi_num = len(set(user_answer) & set(stand_answer))
                rec_num1 += sig_ubi_num
                rec_num2 += len(set(user_answer) | set(stand_answer))
                sig_rate = round(sig_ubi_num * 100 / len(set(user_answer) | set(stand_answer)), 2)
                answer_lists.append(f"{sig_rate} %")
                if user_answer == stand_answer:
                    right_num += 1
                    tag_right_num += len(stand_answer)
                    user_all += len(user_answer)
                else:
                    error_recode.append(str(index + 1))
                    for i in user_answer:
                        if i in stand_answer:
                            tag_right_num += 1

                    if map_error_q_id.get(str(index + 1)) is None:
                        map_error_q_id[str(index + 1)] = 1
                    else:
                        map_error_q_id[str(index + 1)] = map_error_q_id[str(index + 1)] + 1
                t_map = {}
                for i in user_answer:
                    t_map[i] = 1
                if map_qid.get(index + 1) is None:
                    map_qid[index + 1] = {"nums": 1, "recode": t_map}
                else:
                    map_qid[index + 1]["nums"] = map_qid[index + 1]["nums"] + 1
                    dict1 = t_map
                    dict2 = map_qid[index + 1]["recode"]
                    all_keys = set(dict1) | set(dict2)

                    # 合并字典
                    merged_dict = {key: dict1.get(key, 0) + dict2.get(key, 0) for key in all_keys}

                    map_qid[index + 1]["recode"] = merged_dict

                tag_right_num_all += sig_ubi_num
            q_right_rate = round(right_num * 100 / len(stand_map), 2)
            t_right_rate = round(rec_num1 * 100 / rec_num2, 2)
            out_lis.extend([f"{q_right_rate} %", f"{t_right_rate} %", "\n".join(error_recode)])
            out_lis.extend(answer_lists)
            self.success_lis.append(out_lis)
        out_headers = ["项目ID", "场次ID", "题目ID", "姓名", "电话", "基地", "服务商", "题目正确率", "标签正确率",
                       "错误题号"] + _out_headers

        out_folder = self.make_out_path(self.save_path, ["script_3"])
        save_file_csv = self.folder.merge_path([out_folder, f"1556_{sheet}_result_{filename}.csv"])
        self.csv.write_to_csv(save_file_csv, self.success_lis, out_headers)
        self.success_lis = []

        for q_id, val in map_qid.items():
            h_lis = [
                "题号",
                "错误次数",
                "答题次数",
                "正确率",
                "标准答案"
            ]
            error_nums = map_error_q_id.get(str(q_id), 0)
            replay_nums = answer_times
            new_rate = round((replay_nums - error_nums) * 100 / replay_nums, 2)

            s_ans = "|".join(stand_map.get(q_id))
            tmp = [q_id, error_nums, replay_nums, f"{new_rate} %", s_ans]
            recode_lis = dict(sorted(val["recode"].items(), key=lambda item: item[1], reverse=True))
            # print(recode_lis)
            re_num = 1
            for k, v in recode_lis.items():
                h_lis.extend([
                    f"标签{re_num}",
                    f"标签{re_num}出现次数",
                ])
                tmp.extend([k, v])
                re_num += 1
            tmp = [str(i).strip("\n") for i in tmp]

            self.success_lis.append(h_lis)
            self.success_lis.append(tmp)
        save_file_txt = self.folder.merge_path([out_folder, f"1556_{sheet}_error_result_{filename}.txt"])
        self.save_result(save_file_txt, self.success_lis)
        self.success_lis = []

        zip_file = f"{self.save_path}/{filename}.zip"
        self.zip.zip_files(out_folder, zip_file)
        self.folder.remove(folder=out_folder)
        return f"{filename}.zip"

    def check_keys(self, data, key_lis):
        """

        :param data:
        :param key:
        :return:
        """
        for key in key_lis:
            if not data.get(key):
                raise NameError(key)

    def process(self, data):
        """

        :return:
        """

        data["Desc"] = self.desc
        self.save_path = "static/download"
        self.folder.create_folder(self.save_path)

        self.check_keys(data, ["input_file", "stand_file", "sheet"])

        input_file = "tmp/uploads/" + data["input_file"]
        stand_file = "tmp/uploads/" + data["stand_file"]
        sheet = data["sheet"]
        file_obj = PathParser(input_file)
        filename = f"result_{file_obj.name}_{self.time.get_normal_date()}"
        download_file = ""
        download_file = self.dp(input_file, stand_file, sheet, filename)
        download_file = download_file.replace('\\', '/')
        data["ScriptResults"] = download_file
        return data


if __name__ == '__main__':
    s = Solution()
    data = {
        "input_file": r"C:\Users\JHC\Desktop\dest\celery_test\tmp\uploads\3708f9df-be5a-406e-9ac4-5fec0ff46f64_考试结果-20241030181619.csv",
        "stand_file": r"C:\Users\JHC\Desktop\dest\celery_test\tmp\uploads\0366b6ff-e4d5-4a7d-b4c0-7f97605b0810_AIGC黑白盒审核练习-百度.xlsx",
        "sheet": "准入30题",
    }
    s.process(data)
